package com.liurong.netty.v2.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ChatServer {
	private int port;

	public void setPort(int port) {
		this.port = port;
	}

	private EventLoopGroup bossGroup = new NioEventLoopGroup();
	private EventLoopGroup workerGroup = new NioEventLoopGroup();

	public void run() {
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			// 设置工作线程
			serverBootstrap.group(bossGroup, workerGroup);
			// 设置信道模式
			serverBootstrap.channel(NioServerSocketChannel.class);
			serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
			serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
			// 设置处理模式
			serverBootstrap.childHandler(new ChatServerInitializer());
			//
			System.out.println("----------------charserver  start----------------");
			ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

			channelFuture.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
			System.out.println("---------- charserver  close------------");
		}
	}

	public static void main(String[] args) {
		ChatServer chatServer = new ChatServer();
		chatServer.setPort(8888);
		chatServer.run();
	}
}
